<?php

namespace app\admin\service\goods;

use app\traits\Result;
use app\admin\model\GoodsAttrValueType;
use app\admin\model\GoodsAttrValue;
use app\admin\model\GoodsAttrType;
use think\Exception;
use app\common\model\GoodsAttr;


class AttrService
{
    use Result;

    /**
     * 添加/编辑 ---- 规格（属性）分类
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeAttrType($data,$scene='add'){
      //  $data['state'] = isset( $data['state'])? $data['state']:0;
        $data['update_time'] = time();

        $model = new GoodsAttrType(); //实例化
        if(!empty($data) && !empty($data['name'])) {
            if ($scene == 'add') {
                $data['create_time'] = time();

                $result = $model->save($data);
                if ($result) {
                    return Result::success('添加成功');
                } else {
                    return Result::error('添加失败');
                }
            } else {
                //$result = $model->where(['id'=>$data['id']])->find();
               // print_r($data);exit;
                unset($data['token']);
                $result = $model->exists(true)->update($data);
                //   $result->save($data);
                if ($result) {
                    return Result::success('编辑成功');
                } else {
                    return Result::error('编辑失败');
                }
            }
        }
        return false;
    }

    /**
     * 添加/编辑 ---- 规格（属性）值分类
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeAttrValueType($data,$scene='add'){
        //  $data['state'] = isset( $data['state'])? $data['state']:0;
        $data['update_time'] = time();

        $model = new GoodsAttrValueType(); //实例化
        if(!empty($data) && !empty($data['name'])) {
            if ($scene == 'add') {
                $data['create_time'] = time();

                $result = $model->save($data);
                if ($result) {
                    return Result::success('添加成功');
                } else {
                    return Result::error('添加失败');
                }
            } else {
                //$result = $model->where(['id'=>$data['id']])->find();
                unset($data['token']);
                $result = $model->exists(true)->update($data);
                //   $result->save($data);
                if ($result) {
                    return Result::success('编辑成功');
                } else {
                    return Result::error('编辑失败');
                }
            }
        }
        return false;
    }

    /**
     * 添加/编辑 ---- 规格（属性）值
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeAttrValue($data,$scene='add'){
        //  $data['state'] = isset( $data['state'])? $data['state']:0;
        $data['update_time'] = time();

        $model = new GoodsAttrValue(); //实例化
        if(!empty($data) && !empty($data['name'])) {
            if ($scene == 'add') {
                $data['create_time'] = time();

                $result = $model->save($data);
                if ($result) {
                    return Result::success('添加成功');
                } else {
                    return Result::error('添加失败');
                }
            } else {
                //$result = $model->where(['id'=>$data['id']])->find();
                unset($data['token']);
                $result = $model->exists(true)->update($data);
                //   $result->save($data);
                if ($result) {
                    return Result::success('编辑成功');
                } else {
                    return Result::error('编辑失败');
                }
            }
        }
        return false;
    }

    /**
     * 获取商品属性 集合
     * array
    **/

    public static function getAttrArry($params){
        try {
            //获取状态为1的属性值
            $value = GoodsAttrValueType::where(['state' => 1,'type_id'=>$params['type']])->field('id,name,type_id,sort')->order('sort', 'ASC')->select()->toArray();
            $data = array();
            foreach ($value as $k => $e) {
                $data[$k]['id']=$e['id'];
                $data[$k]['key']=$e['name'];
                $data[$k]['sort']=$e['sort'];
                $data[$k]['checkedAttr']=[];//已选择的属性
                $data[$k]['value'] = self::getAttrValue($params['goods_id'])[$e['id']];
            }
            $attr_arr = GoodsAttr::where(['goods_id' => $params['goods_id']])->select()->toArray();

            return ['attr_arry'=>$data,'goods_attr'=>$attr_arr];
        }catch (Exception $exception){
            return $exception->getMessage();
        }

    }

    /**
     * 获取属性值
     * array
     **/

    public static  function getAttrValue($goods_id){
        try {
            $goods_attr = self::getAttrId($goods_id);
           // print_r($goods_attr);exit;
            //获取状态为1的属性值
            $value = GoodsAttrValue::where(['state' => 1])->field('id,name,type_id,sort')->order('sort', 'ASC')->select()->toArray();
            $data = array();
            foreach ($value as $k => &$e) {
              //  $data[$e['type_id']][$e['id']] = $e;
                $e['checked'] = 0;
                if(!empty($goods_attr[$e['id']])) {
                    if ($goods_attr[$e['id']] == $e['id']) {
                        $e['checked'] = 1;
                    }
                }
                $data[$e['type_id']][] = $e;
            }
            return $data;
        }catch (Exception $exception){
            return $exception->getMessage();
        }
    }

    /**
     * 获取商品属性值id
     */
    public static function getAttrId($goods_id){

        $attr_arr = GoodsAttr::where(['goods_id' => $goods_id])->field('arrt_id')->select()->toArray();
        $attr_arr = array_column($attr_arr, 'arrt_id');
        $attr_arr = implode(',', $attr_arr);
        $attr_arr = implode(",", array_unique(explode(',', $attr_arr)));
        $attr_arr = explode(",", $attr_arr);
        $data=[];
        foreach ($attr_arr as $key=>$vs){
            $data[$vs]=$vs;
        }

        return $data;
    }
}